import { tt } from "../../ttapi_interface/ttapi.js";
import * as tt2 from "../../ttapi_layer2/ttlayer2.js";
import { EUI_Style } from "./EUI_Style.js";


export class EUI_FileItem {
    name: string;
    folder: boolean = false;
    empty: boolean = false;
    expend: boolean = false;
    deep: number = 1
}
export class EUI_FileTree extends tt2.QUI_Panel_Scroll_Unlimit<EUI_FileItem> {
    constructor() {
        super(null);
        this.ResetItemFunc(this._updateItem.bind(this));
    }
    private _mapicon: { [id: string]: tt.Sprite } = {}
    AddIcon(ext: string, sprite: tt.Sprite): void {
        let _ext = ext.toLowerCase();
        if (_ext.indexOf(".") != 0)
            throw new Error("ext must be index of .");
        this._mapicon[_ext] = sprite;
    }
    OnPick: (item: EUI_FileItem) => void;
    _pick: EUI_FileItem;
    //无限滚动主要要写这个
    private _updateItem(item: EUI_FileItem, ui: tt2.QUI_IElement, id: number, pick: boolean): tt2.QUI_IElement {

        let con: tt2.QUI_Container = ui as tt2.QUI_Container;
        if (con == null) {//初始化外观控件
            con = new tt2.QUI_Container();
            con.localRect.setHPosFill();
            con.localRect.setVPosByTopBorder(16);
            //标签
            {
                let conlabel = new tt2.QUI_Label(EUI_Style.font);
                conlabel.localRect.setVPosFill();
                conlabel.localRect.setHPosFill(16);
                //conlabel.fontScale = new tt.Vector2(2, 2)
                con.addChild(conlabel);
                conlabel.halign = tt2.QUI_HAlign.Left;
            }
            //文件夹折叠按钮
            {
                let folderToggle = new tt2.QUI_Toggle();
                folderToggle.ElemFalse = new tt2.QUI_Image(EUI_Style.btnroundsmall_no2);
                folderToggle.ElemFalseDown = new tt2.QUI_Image(EUI_Style.btnroundsmall_no2);
                folderToggle.ElemTrue = new tt2.QUI_Image(EUI_Style.btnroundsmall2);
                folderToggle.ElemTrueDown = new tt2.QUI_Image(EUI_Style.btnroundsmall2);
                folderToggle.OnChange = (v) => {
                    let id = (con as any)._id as number;
                    let item = (con as any)._item as EUI_FileItem;
                    if (v == false) {
                        this.ClosePath(id, item);
                    }
                    else {
                        this.OpenPath(id, item);
                    }
                }
                //let icon = new tt2.QUI_Image(EUI_Style.btnroundsmall_no2);
                folderToggle.localRect.setByRect(new tt.Rectangle(0, 0, 16, 16));
                con.addChild(folderToggle);
            }
            //图标
            {
                let icon = new tt2.QUI_Image();
                icon.localRect.setByRect(new tt.Rectangle(0, 0, 16, 16));
                con.addChild(icon);
            }
            let overlay = new tt2.QUI_Overlay();
            overlay.localRect.setVPosFill();
            overlay.localRect.setHPosFill(16);
            con.addChild(overlay);

            overlay.OnPress = () => {
                let id = (con as any)._id;
                this.Pick(id);
                this._pick = (con as any)._item as EUI_FileItem;
                if (this.OnPick != null) {

                    this.OnPick(this._pick);
                }
            }
        }
        (con as any)._id = id;

        if (item != null) {//更新控件外观

            con.localRect.setHPosFill(16 * (item.deep - 1), 0);
            (con as any)._item = item;
            let name = tt.PathTool.GetFileName(tt.PathTool.CheckPath(item.name));
            let conlabel = con.getChild(0) as tt2.QUI_Label;
            let folderToggle = con.getChild(1) as tt2.QUI_Toggle;
            let icon = con.getChild(2) as tt2.QUI_Image;
            folderToggle.value = item.expend;
            folderToggle.Enable = item.folder;

            conlabel.text = name;
            if (pick) {
                conlabel.color.R = 0;
                conlabel.color.G = 0;
                conlabel.color.B = 1;
            }
            else {
                conlabel.color.R = 1;
                conlabel.color.G = 1;
                conlabel.color.B = 1;
            }


            //匹配图标
            icon.sprite = null;

            if (item.folder) {
                icon.sprite = null;
            }
            else {
                let ext = tt.PathTool.GetFileNameObj(tt.PathTool.CheckPath(item.name));
                while (ext != null && ext.dotcount > 0) {
                    let exticon = this._mapicon[ext.ext.toLowerCase()];
                    if (exticon != undefined) {
                        icon.sprite = exticon;
                        break;
                    }
                    else {


                    }

                    ext = ext.nextLevel;
                }
            }

        }
        return con;
    }
    private _rootpath: string
    private async OpenPath(iBegin: number, item: EUI_FileItem) {
        if (item.expend == true)
            throw new Error("already expanded.");
        let info = await tt2.QExt_IO.Dir_List(item.name);
        let count = 0;
        for (var i = 0; i < info.dirs.length; i++) {
            let name = tt.PathTool.GetFileName(tt.PathTool.CheckPath(info.dirs[i]))
            if (name.indexOf("$") == 0 || name.indexOf('.') == 0) {
                continue;
            }
            count++;
            let newitem: EUI_FileItem = { "name": info.dirs[i], "folder": true, "deep": item.deep + 1, "empty": false, expend: false }
            this.getItems().splice(iBegin + 1 + i, 0, newitem);
        }
        for (var i = 0; i < info.files.length; i++) {
            let path = info.files[i];
            let name = tt.PathTool.GetFileName(tt.PathTool.CheckPath(info.files[i]))
            if (name.indexOf("$") == 0 || name.indexOf('.') == 0) {
                continue;
            }
            count++;
            let newitem: EUI_FileItem = { "name": path, "folder": false, "deep": item.deep + 1, "empty": false, expend: false }
            this.getItems().splice(iBegin + 1 + i, 0, newitem);
        }
        item.expend = true;
    }
    private async ClosePath(iBegin: number, item: EUI_FileItem) {
        if (item.expend == false)
            throw new Error("already disable expanded.");

        let rcount: number = 0;
        let items = this.getItems();
        while (true) {
            if (iBegin + 1 >= items.length)
                break;
            if (items[iBegin + 1].deep <= item.deep)
                break;

            rcount++;
            items.splice(iBegin + 1, 1);

        }
        item.expend = false;

    }
    getRoot(): string {
        return this._rootpath;
    }
    async SetRoot(path: string): Promise<void> {
        this._rootpath = path;
        this.Clear();

        let infos = await tt2.QExt_IO.Dir_List(this._rootpath);
        let items = this.getItems();


        for (var i = 0; i < infos.dirs.length; i++) {
            let it = infos.dirs[i];
            items.push({ "name": it, "folder": true, "empty": false, deep: 1, expend: false });

        }
        for (var i = 0; i < infos.files.length; i++) {
            let it = infos.files[i];
            items.push({ "name": it, "folder": false, "empty": false, deep: 1, expend: false });
        }
        return;
    }
    getPickFolder(): string {
        if (this._pick == null)
            return null;
        if (this._pick.folder)
            return this._pick.name;
        let _f = tt.PathTool.GetPathName(tt.PathTool.CheckPath(this._pick.name));
        return _f;
    }
    PickByFullName(filename: string): void {
       let path = filename.split("/");
       //not finish.
    }
}